/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.report.business;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import reportcenter.auth.CurrentUser;
import reportcenter.support.dbutil.JPAFactory;
import reportcenter.report.dominio.report.Report;
import reportcenter.report.dominio.column.ReportColum;
import reportcenter.report.dominio.param.ReportParam;
import reportcenter.report.support.query.QueryInterceptor;
import reportcenter.report.support.util.SqlDateToUtilDate;
import reportcenter.report.support.util.StringTransformer;
import reportcenter.support.dbutil.ConnectionManager;
import reportcenter.support.resourceload.DataSourceConfig;

/**
 *
 * @author renan_luz
 */
public class AdminReportDao {
    
//    private List reports = new ArrayList();

    public List<Report> getByRole() {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();

        List<Report> reports = null;
        try {
            Query query = null;
            if (!new CurrentUser().grantedRoles().contains("ROLE_SUPREME")){
                query = JPAFactory.getInstance().getManager().createQuery("select report from Report as report left join report.idRole as roles where roles.roleName in(" + new CurrentUser().grantedRoles() + ")");
            }else{
                query = JPAFactory.getInstance().getManager().createNamedQuery("Report.findAll");
            }

            reports = query.getResultList();

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
        
        
        return reports;
    }
    
    public List<Report> getAll() {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();

        List<Report> reports = null;
        try {
            Query query = JPAFactory.getInstance().getManager().createNamedQuery("Report.findAll");
            reports = query.getResultList();

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
        
        
        return reports;
    }
    
    public Report[] getAllAsArray() {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();

        List<Report> reports = null;
        try {

            Query query = JPAFactory.getInstance().getManager().createNamedQuery("Report.findAll");
            reports = query.getResultList();

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
        
        
        return (Report[]) reports.toArray(new Report[0]);
    }

    public void add(Report rp) {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();
        try {
            Statement stmt = null;
            ResultSetMetaData meta = null;
            new ConnectionManager(new DataSourceConfig(rp.getIdD()));
            Connection conn = ConnectionManager.ds.getConnection();
            stmt = conn.createStatement();
            
            //The magic
            ResultSet rs = stmt.executeQuery(new QueryInterceptor().defaultParamValues(rp.getQuery()));
            meta = rs.getMetaData();
            
            //zerar collections
            if(rp.getReportColumCollection() != null){
                new ReportColumDao().deleteCollection(rp.getReportColumCollection());
                if(rp.getReportParamCollection() != null){
                    new ReportParamDao().deleteCollection(rp.getReportParamCollection());
                }
            }
            
            rp.setReportColumCollection(null);
            rp.setReportParamCollection(null);
            
            //obter informações sobre as colunas a partir de metadata
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                
                StringTransformer conversor = new SqlDateToUtilDate();
                rp.addReportColumn(ReportColum.criarCom() //
                        .clazz(conversor.transform(meta.getColumnClassName(i))) //
                        .columnName(meta.getColumnName(i)) //
                        .width(30) //
                        .columnDescr(meta.getColumnName(i)) //
                        .columnPosition(i) //
                        .create());
                
            }
            
            //Setar parametros do relatorio
            for(ReportParam param : new QueryInterceptor().searchParameters(rp.getQuery())  ){
                rp.addReportParam(param);
            }

//            for(ReportColum col : rp.getReportColumCollection()){
//                System.out.println("Coluna -> " + col.getColumnName());
//            }
            
            JPAFactory.getInstance().getManager().persist(rp);
//            this.reports.add(rp);

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
    }

    public void delete(Report report) {
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();
        try {
            
            JPAFactory.getInstance().getManager().remove(report);
//            this.reports.remove(report);

            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }
    }
}
